<template>
	<view class="quotation">
		<view class="container">
			<!-- <uni-card class="header-card">
				<uni-list :border="false" class="header" v-if="product.id">
					<uni-list-item :border="false" link to="/pages/productList/productList?type=selector">
						<template v-slot:header>
							<view class="image-box" v-if="product.photo">
								<image :src="image_base64(product.photo)"></image>
							</view>
							<view class="image-default-box" v-else>
								<image mode="widthFix" style="width: 40rpx;" src="@/static/image/default.png"></image>
							</view>
						</template>
						<template v-slot:body>
							<view class="product-content">
								<view class="product-name">
									{{product.name}}
								</view>
							</view>
						</template>
					</uni-list-item>
				</uni-list>
				<uni-list :border="false" v-else>
					<uni-list-item :border="false" title="请选择产品" link
						to="/pages/productList/productList?type=selector"></uni-list-item>
				</uni-list>
			</uni-card> -->
			<uni-card class="form" v-if="has_multi_spec && lines.length > 0">
				<uni-table border stripe emptyText="暂无更多数据">
					<!-- 表头行 -->
					<uni-tr>
						<uni-th width="100" align="center">型号</uni-th>
						<uni-th width="100" align="center">数量</uni-th>
						<uni-th width="100" align="center">销售单价</uni-th>
						<uni-th width="100" align="center">销售金额</uni-th>
					</uni-tr>
					<!-- 表格数据行 -->
					<uni-tr v-for="item in lines" :key="item.id">
						<uni-td align="center">{{item.name}}</uni-td>
						<uni-td align="center">
							<input type="digit" v-model="item.product_qty" placeholder="请输入数量" placeholder-class="placeholder" />
						</uni-td>
						<uni-td align="center">
							<text>{{item.proposed_price_unit}}</text>
						</uni-td>
						<uni-td align="center">
							<text>{{item.proposed_sale_amount}}</text>
						</uni-td>
					</uni-tr>
				</uni-table>
			</uni-card>
			<uni-card class="form" v-if="product && product.id && (fields.length > 0 || fields2.length > 0)" v-show="show_form.length > 0">
				<quotation-fields class="fields1" :isComputed="isComputed" :is_customized="is_customized" :isPreview="isPreview" :is_customer="is_customer"
					ref="quotationFieldsRef" :fields="fields_show" :fields_default="fields_default"
					@loaded="quotationFieldsLoaded"></quotation-fields>
			</uni-card>
			<!-- <uni-card class="form" v-if="product && product.id && Object.keys(fields2).length > 0">
				<quotation-fields :is_customer="is_customer" ref="quotationFields2Ref" :fields="fields2"></quotation-fields>
			</uni-card> -->
			<uni-card class="form">
				<picker class="picker" :range="destinations" range-key="name" @change="destinationChange">
					<uni-list-item link>
						<template v-slot:header>
							<view class="label">选择地址:</view>
						</template>
						<template v-slot:body>
							<view class="sign-row">
								<input class="input" placeholder="请选择区域" placeholder-style="color: #bdbdbd;" disabled
									:value="destination.name" />
							</view>
						</template>
					</uni-list-item>
				</picker>
				<picker class="picker" :range="taxs" range-key="name" @change="taxChange" disabled>
					<uni-list-item link>
						<template v-slot:header>
							<view class="label">开票选择:</view>
						</template>
						<template v-slot:body>
							<view class="sign-row">
								<input class="input" placeholder="请选择开票方式" placeholder-style="color: #bdbdbd;" disabled
									:value="tax.name" />
							</view>
						</template>
					</uni-list-item>
				</picker>
				<uni-list-item :link="!is_customer" :clickable="!is_customer" @click="toChoosePartner">
					<template v-slot:header>
						<view class="label">选择客户:</view>
					</template>
					<template v-slot:body>
						<view class="sign-row">
							<view class="word-area" v-if="partner.name_mobile">
								{{partner.name_mobile}}
							</view>
							<input class="input" placeholder="选填" placeholder-style="color: #bdbdbd;" disabled
								:value="partner.name_mobile" v-else />
						</view>
					</template>
				</uni-list-item>
			</uni-card>
			<uni-card class="form" v-if="product.note">
				<div class="note-container">
					<div class="note-title">说明:</div>
					<rich-text :nodes="product.note" class="note"></rich-text>
				</div>
			</uni-card>
		</view>
		<view class="footer">
			<view class="btn" @click="beforeSubmit">预报价</view>
			<view class="btn" @click="preview">预览报价</view>
			<view class="btn" @click="submit">提交报价</view>
		</view>
		<safe-area></safe-area>
	</view>
</template>

<script>
	import {
		receivingRegion,
		getTaxsPicker,
		productDetail,
		userAuth,
		getCustomerList,
	} from "@/api/search_read.js";
	import {
		productFields,
		quotationCompute,
		quotationCreate,
		previewRecord,
	} from "@/api/call_kw.js";
	import _, { filter } from "lodash";
	export default {
		data() {
			return {
				// 类型 previewRecord 商机记录
				type: '',
				product: {},
				id: '',
				// 已完成预报价
				isComputed: false,
				// 已操作预览报价
				isPreview: false,
				// 是否多规格
				has_multi_spec: false,
				// 型号
				lines: [],
				// 页面需提交参数
				fields: [

				],
				// 页面参数默认值
				fields_default: {},
				// 显示的列
				show_form: [],
				// 预报价生成参数
				fields2: [

				],
				//税率信息
				tax: {},
				// 收货地址
				destination: {},
				// 当前登录用户是否为客户
				is_customer: false,
				// 客户列表
				customerList: [],
				// 客户
				partner: {},
				// 可选区域列表
				destinations: [],
				// 可选税率列表
				taxs: [],
				// 是否定制类
				is_customized: false,
			}
		},
		computed: {
			fields_show() {
				return [...this.fields, ...this.fields2];
			},
		},
		async onLoad(options) {
			await this.getConfig();
			if (options.record_id) {
				this.type = 'previewRecord';
				this.id = options.record_id || '';
				this.isComputed = true;
				this.isPreview = true;
			}
			if (options.id) {
				this.getProduct(options.id);
			}
			uni.$on('chooseProduct', (item) => {
				this.getProduct(item.id);
			})
			uni.$on('choosePartner', (item) => {
				this.partner = item;
				let name = item.name || '/';
				let mobile = item.mobile || '/';
				this.partner.name_mobile = `${name}(${mobile})`;
			})
			uni.$on('preview', () => {
				this.isPreview = true;
			})
		},
		onUnload() {
			uni.$off('chooseProduct');
			uni.$off('choosePartner');
			uni.$off('preview');
		},
		methods: {
			// 获取配置
			async getConfig() {
				return new Promise((resolve) => {
					Promise.all([this.getTaxs(), this.getUser(), this.getCustomerList(), this.getDestinations()]).finally(
						() => {
							resolve(true);
						})
				})
			},
			// 获取产品
			getProduct(id) {
				productDetail({
					id,
				}).then(res => {
					if (res.data?.result?.length >= 1) {
						let detail = res?.data?.result?.records?.[0];
						this.product = detail;
						uni.setNavigationBarTitle({
							title: detail?.name || '预报价',
						})
						if (this.type === 'previewRecord') {
							this.getRecord(this.id);
						} else {
							this.getProductFields(id);
						}
					} else {
						uni.showToast({
							icon: 'none',
							title: '未获取产品详情',
						})
					}
				}).catch(() => {
					uni.showToast({
						icon: 'none',
						title: '系统错误',
					})
				})
			},
			// 获取预报价记录
			getRecord(id) {
				return new Promise((resolve) => {
					previewRecord({
						id: Number(id),
					}).then(res => {
						if (res.data?.result) {
							if (res.data?.result?.success) {
								let record = res?.data?.result || {};
								// 型号部分
								this.has_multi_spec = record?.lines?.length > 0 || false;
								this.is_customized = record?.datas?.display_type_name === '定制类';
								let lines = [];
								record?.lines?.forEach(x => {
									let obj = {};
									x.forEach(y => {
										obj[y.field_name] = y?.value;
									})
									lines.push(obj);
								})
								this.lines = lines.map(x => {
									x.proposed_price_unit = x?.proposed_price_unit?.toFixed?.(2);
									x.proposed_sale_amount = x?.proposed_sale_amount?.toFixed?.(0);
									return x;
								});
								// fields部分
								let fields = record?.fields?.order?.map(x => {
									x.do_type = 'edit';
									x.sequence = record?.order?.find(y => y.field_name === x.field_name)?.sequence;
									return x;
								}) || [];
								this.fields = fields;
								let fields_default = {};
								record?.order?.forEach(x => {
									fields_default[x.field_name] = x?.value;
								})
								this.fields_default = fields_default;
								// fields2部分
								let fields2 = record?.order?.filter(x => x?.field_name)?.filter(x => this.fields.concat([{
									field_name: 'destination'
								}, {
									field_name: 'partner_id'
								}, {
									field_name: 'tax_id'
								}]).findIndex(y => y
									.field_name === x?.field_name) === -1)?.map(x => {
									x.do_type = 'readonly';
									x.show_type = 'signImport';
									return x;
								}) || [];
								this.fields2 = fields2;
								// 地址、客户部分
								let idx = this.destinations?.findIndex(x => x.name === record?.order?.find?.(y => y
									.field_name === 'destination')?.value);
								if (idx > -1) {
									this.destination = this.destinations?.[idx] || {};
								}
								let idx2 = this.taxs?.findIndex(x => x.name === record?.order?.find?.(y => y
									.field_name === 'tax_id')?.value);
								if (idx2 > -1) {
									this.tax = this.taxs?.[idx2] || {};
								}
								let idx3 = this.customerList?.findIndex(x => x.name === record?.order?.find?.(y => y
									.field_name === 'partner_id')?.value);
								if (idx3 > -1) {
									this.partner = this.customerList?.[idx3] || {};
									let name = this.customerList?.[idx3]?.name || '/';
									let mobile = this.customerList?.[idx3]?.mobile || '/';
									this.partner.name_mobile = `${name}(${mobile})`;
								}
							} else {
								uni.showToast({
									icon: 'none',
									title: res.data?.result?.message || '获取商机记录失败',
								})
							}
						} else {
							uni.showToast({
								icon: 'none',
								title: res?.data?.error?.data?.message || '获取商机记录失败',
							})
						}
					}).catch((error) => {
						console.error(error);
						uni.showToast({
							icon: 'none',
							title: '系统错误',
						})
					}).finally(() => {
						resolve(true);
					})
				})
			},
			// 获取客户列表
			getCustomerList() {
				return new Promise((resolve) => {
					getCustomerList({
						limit: 0,
						offset: 0,
					}).then(res => {
						if (res.data?.result) {
							this.customerList = this.customerList.concat(res?.data?.result?.records.map(x => {
								x.company_name = x.company_id?.[1] || '';
								x.avatarUrl = x.avatar_256 ? this.image_base64(x.avatar_256) : '';
								return x;
							}));
						} else {
							uni.showModal({
								title: '错误提示',
								content: res?.data?.error?.data?.message || '获取客户列表失败',
							})
						}
					}).catch(() => {
						uni.showToast({
							icon: 'none',
							title: '系统错误',
						})
					}).finally(() => {
						resolve(true);
					})
				})
			},
			// 获取产品需报价列
			getProductFields(id) {
				this.fields = [];
				this.lines = [];
				uni.showLoading({
					title: '加载中...'
				});
				productFields({
					id,
				}).then(res => {
					if (res.data.result) {
						const obj = res.data?.result || {};
						this.id = obj?.datas?.id || '';
						let fields = obj?.fields?.order.map(x => {
							x.do_type = 'edit';
							return x;
						}) || [];
						this.fields = fields?.filter(x => x.field_name !== 'destination');
						this.fields_default = obj?.datas || {};
						this.has_multi_spec = obj?.datas?.has_multi_spec || false;
						this.is_customized = obj?.datas?.display_type_name === '定制类';
						this.lines = obj?.fields?.lines.map(x => {
							x.product_qty = '';
							x.proposed_sale_amount = '';
							x.sale_state = '';
							return x;
						}) || [];
						uni.hideLoading();
					} else {
						uni.hideLoading();
						uni.showToast({
							icon: 'none',
							title: res.data?.error?.data?.message || '预报价失败',
						})
					}
				}).catch((e) => {
					uni.hideLoading();
					uni.showToast({
						icon: 'none',
						title: '系统错误',
						duration: 3000,
					})
				})
			},
			// 获取区域列表
			getDestinations() {
				return new Promise((resolve) => {
					receivingRegion().then(res => {
						if (res.data?.result && res.data?.result?.length >= 1) {
							this.destinations = res.data?.result?.records || [];
						} else {
							uni.showToast({
								icon: 'none',
								title: '没有获取到区域信息',
							})
						}
					}).catch(() => {
						uni.showToast({
							icon: 'none',
							title: '系统错误',
						})
					}).finally(() => {
						resolve(true);
					})
				})
			},
			// 获取税率列表
			getTaxs() {
				return new Promise((resolve) => {
					getTaxsPicker().then(res => {
						if (res.data?.result && res.data?.result?.length >= 1) {
							this.taxs = res.data?.result?.records || [];
							this.tax = this.taxs?.[0] || {};
						} else {
							uni.showToast({
								icon: 'none',
								title: '没有获取到税率列表',
							})
						}
					}).catch(() => {
						uni.showToast({
							icon: 'none',
							title: '系统错误',
						})
					}).finally(() => {
						resolve(true);
					})
				})
			},
			taxChange(e) {
				let idx = Number(e.detail.value);
				this.tax = this.taxs?.[idx] || {};
			},
			// 选择客户
			toChoosePartner: _.debounce(function() {
				uni.navigateTo({
					url: '/pages/customer-selector/customer-selector',
				})
			}, 300),
			// 获取用户信息
			getUser() {
				return new Promise((resolve) => {
					userAuth().then(res => {
						if (res.data.result?.length >= 1) {
							let obj = res?.data?.result?.records?.[0] || {};
							this.is_customer = obj?.enable_mobile_customer || false;
							if (obj?.enable_mobile_customer) {
								this.partner = obj;
								let name = obj.name || '/';
								let mobile = obj.mobile || '/';
								this.partner.name_mobile = `${name}(${mobile})`;
							}
						} else {
							uni.showToast({
								icon: 'none',
								title: '未获取到用户信息',
							})
						}
					}).catch(() => {
						uni.showToast({
							icon: 'none',
							title: '系统错误',
						})
					}).finally(() => {
						resolve(true);
					})
				})
			},
			// 选择区域
			destinationChange(e) {
				let idx = Number(e.detail.value);
				this.destination = this.destinations?.[idx] || {};
			},
			beforeSubmit: _.debounce(function() {
				if (!this.id) {
					uni.showToast({
						icon: 'none',
						title: '请选择产品',
					})
					return;
				}
				if (!this.destination.id) {
					uni.showToast({
						icon: 'none',
						title: '请选择地址',
					})
					return;
				}
				let form = this.$refs?.quotationFieldsRef?.getForm?.() || [];
				let requireds_all = this.$refs?.quotationFieldsRef?.labelRequireds || [];
				let requireds = form.filter(x => requireds_all.includes(x.field_name));
				if(requireds.some(x => x.value === '' || x.value === undefined || x.value === null)) {
					uni.showToast({
						icon: 'none',
						title: '请填写必填信息',
					})
					return;
				}
				let fields = {};
				form.forEach(x => {
					fields[x.field_name] = x.value;
				})
				let order = {
					partner_id: this.partner.id,
					destination: this.destination.id,
					tax_id: this.tax.id,
					...fields
				}
				uni.showLoading({
					title: '预报价中'
				});
				quotationCompute({
					id: this.id,
					order,
					lines: this.lines,
				}).then(res => {
					if (res.data?.result) {
						if (res?.data?.result?.success) {
							let obj = res.data?.result || {};
							let fields = obj?.order?.filter(x => x.field_name)?.filter(x => this.fields.concat([{
								field_name: 'destination'
							}, {
								field_name: 'partner_id'
							}, {
								field_name: 'tax_id'
							}]).findIndex(y => y
								.field_name === x.field_name) === -1)?.map(x => {
								x.do_type = 'readonly';
								x.show_type = 'signImport';
								return x;
							}) || [];
							this.fields2 = fields;
							obj?.lines?.forEach(x => {
								let idx = this.lines?.findIndex?.(y => y.id === x.find(z => z.field_name === 'id').value);
								if (idx > -1) {
									this.lines[idx].proposed_price_unit = x?.find?.(y => y.field_name ===
											'proposed_price_unit')
										?.value?.toFixed(2) || 0;
									this.lines[idx].proposed_sale_amount = x?.find?.(y => y.field_name ===
											'proposed_sale_amount')
										?.value?.toFixed(0) || 0;
								}
							})
							this.isComputed = true;
							uni.hideLoading();
						} else {
							uni.hideLoading();
							uni.showToast({
								icon: 'none',
								title: res.data?.result?.message || '预报价失败',
							})
						}
					} else {
						uni.hideLoading();
						uni.showToast({
							icon: 'none',
							title: res.data?.error?.data?.message || '预报价失败',
							duration: 3000,
						})
					}
				}).catch((e) => {
					uni.hideLoading();
					uni.showToast({
						icon: 'none',
						title: '系统错误',
						duration: 3000,
					})
				})
			}, 300),
			preview: _.debounce(function() {
				if (!this.isComputed) {
					uni.showToast({
						icon: 'none',
						title: '请先完成预报价!',
					})
					return;
				}
				uni.navigateTo({
					url: `/pages/quotationPreview/quotationPreview?id=${this.id}`,
				})
			}, 300),
			submit: _.debounce(function() {
				if (!this.isComputed) {
					uni.showToast({
						icon: 'none',
						title: '请先完成预报价!',
					})
					return;
				}
				quotationCreate({
					id: this.id,
				}).then(res => {
					if (res.data?.result) {
						if (res.data.result.success) {
							uni.$emit('previewRecordChange');
							uni.redirectTo({
								url: `/pages/quotationSuccess/quotationSuccess?id=${this.id}`,
							})
						} else {
							uni.showToast({
								icon: 'none',
								title: res.data?.result?.message || '获取失败',
							})
						}
					} else {
						uni.showToast({
							icon: 'none',
							title: res.data?.error?.data?.message || '获取失败',
						})
					}
				})
			}, 300),
			image_base64(photo) {
				return 'data:image/jpeg;base64,' + photo;
			},
			// 报价列加载完成
			quotationFieldsLoaded(e) {
				this.show_form = e;
			}
		},
	}
</script>

<style lang="scss" scoped>
	.quotation {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;

		.container {
			width: 100%;
			flex: 1;
			overflow-y: auto;

			/deep/.uni-card {
				box-shadow: unset !important;
				border-radius: 20rpx;
				border: 0 !important;

				&>view {
					padding: 0 !important;
				}
			}

			.header-card {
				/deep/.uni-card {
					padding: 0 !important;
				}

				.header {
					/deep/.uni-list-item__container {
						padding: 44rpx !important;
					}

					.image-box {
						width: 130rpx;
						height: 130rpx;

						image {
							width: 130rpx;
							height: 130rpx;
						}
					}

					.image-default-box {
						width: 130rpx;
						height: 130rpx;
						display: flex;
						justify-content: center;
						align-items: center;
						background-color: $uni-bg-color;

						image {
							width: 36rpx;
						}
					}

					.product-content {
						width: 100%;
						display: flex;
						flex-direction: column;
						padding-left: 30rpx;
						justify-content: center;

						.product-name {
							padding: 6rpx;
							word-break: break-all;
							font-size: 38rpx;
							color: #34353A;
						}
					}
				}
			}

			.header-info {
				width: 100%;
				box-sizing: border-box;
				padding: 30rpx 0;
				display: flex;

				.image-box {
					flex-shrink: 0;
					width: 200rpx;
					height: 200rpx;

					image {
						width: 200rpx;
						height: 200rpx;
					}
				}

				.image-default-box {
					flex-shrink: 0;
					width: 200rpx;
					height: 200rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					background-color: $uni-bg-color;
				}

				.product-title {
					width: 100%;
					padding-left: 40rpx;
					box-sizing: border-box;
					display: flex;
					flex-direction: column;

					.product-name {
						margin: 18rpx 0 28rpx;
						font-size: 38rpx;
						word-break: break-all;
						color: #34353A;
					}

					.product-detail {
						font-size: 24rpx;
						word-break: break-all;
						color: #B1B0B3;
					}
				}
			}

			.form {
				/deep/.uni-card {
					padding: 0 !important;
				}

				.form-title {
					padding: 40rpx 0;
					display: flex;
					align-items: center;
					font-size: 32rpx;
					color: #34353A;

					&::before {
						content: '';
						flex-shrink: 0;
						width: 8rpx;
						height: 50rpx;
						background-color: #3F7CFB;
						border-radius: 4rpx;
						margin-right: 14rpx;
					}
				}

				.label {
					font-size: 32rpx !important;
					color: black !important;
					flex-shrink: 0;
				}

				.sign-row {
					flex: 1;
					padding-left: 10rpx;

					.word-area {
						width: 100%;
						text-align: right;
						word-break: break-all;
					}

					.input {
						width: 100%;
						text-align: right;
					}
				}

				.note-container {
					width: 100%;
					box-sizing: border-box;
					padding: 30rpx;

					.note-title {
						font-size: 32rpx;
						color: black !important;
						margin-bottom: 20rpx;
					}

					.note {
						width: 100%;
						white-space: pre-wrap;
					}
				}
			}

			.fields1 {
				/deep/.quotation-fields {
					uni-list {
						.uni-list {
							flex-wrap: wrap;
							flex-direction: row;
						}
					}
				}
			}
		}


		.footer {
			width: 100%;
			padding: 30rpx 0;
			flex-shrink: 0;
			display: flex;
			justify-content: center;
			align-items: center;

			.btn {
				height: 100%;
				height: 80rpx;
				line-height: 80rpx;
				text-align: center;
				background-color: white;
				border-radius: 10rpx;
				font-size: 28rpx;
				color: white;
				background-color: rgb(7, 193, 96);
				width: 220rpx;

				&:nth-child(2) {
					margin-left: 18rpx;
				}

				&:last-child {
					margin-left: 18rpx;
					background-color: #3F7CFB !important;
				}
			}
		}
	}

	/deep/.uni-table {
		min-width: unset !important;
		
		.uni-table-td,
		.uni-table-th {
			font-size: 26rpx !important;
			font-weight: bold;
		}

		.uni-table-td {
			vertical-align: middle;
		}
	}

	/deep/.placeholder {
		color: #bdbdbd;
		overflow: hidden;
		text-overflow: ellipsis;
	}
</style>